using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;
using QQ.Client;
using System;

namespace QQ.Handler
{
    public class HeartBeatHandler : ChannelHandlerAdapter
    {
        public override bool IsSharable => true;
        private readonly ClientCallback clientCallback;
        public HeartBeatHandler(ClientCallback clientCallback, LoginSigInfo loginSigInfo)
        {
            this.clientCallback = clientCallback;
        }
        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt == null) return;
            switch (evt)
            {
                case IdleStateEvent idle:
                    {
                        if (clientCallback.recvHeartBeat == false)
                        {
                            System.Console.WriteLine("没有心跳啦。");
                            clientCallback.DisconnectByServer();
                        }else{
                            clientCallback.HeartBeatTimeOut();
                            clientCallback.recvHeartBeat = false;
                        }
                    }break;
            }
        }
        public override void ChannelActive(IChannelHandlerContext context)
        {
            System.Console.WriteLine("[ChannelActive]连接成功...");
            base.ChannelActive(context);
        }
        public override void ChannelInactive(IChannelHandlerContext context)
        {
            /*try
            {
                context.Channel.CloseAsync().Wait();
                context.Channel.ConnectAsync(context.Channel.RemoteAddress).Wait();
                System.Console.WriteLine("[ChannelInactive]正在断线重连中...");
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("貌似出了点问题...");
            }*/
            Console.WriteLine("ChannelInactive");
            
            base.ChannelInactive(context);
        }

        public override void ChannelUnregistered(IChannelHandlerContext context)
        {
            Console.WriteLine("[ChannelInactive]正在断线重连中...");
            clientCallback.DisconnectByServer();
            base.ChannelUnregistered(context);
        }
    }
}